<template>
  <view class="cu-form-group">
    <view class="title"><text v-if="required" class="text-red">*</text>{{title}}</view>
    <input v-if="type === 'number'" type="number" :maxlength="maxlength" :disabled="disabled" :value="inputValue" @input="onInput" :placeholder="placeholder" :name="name">
    <input v-if="type === 'idcard'" type="idcard" :maxlength="maxlength" :disabled="disabled" :value="inputValue" @input="onInput" :placeholder="placeholder" :name="name">
    <input v-if="type === 'digit'" type="digit" :maxlength="maxlength" :disabled="disabled" :value="inputValue" @input="onInput" :placeholder="placeholder" :name="name">
    <input v-if="type === 'safe-password'" type="safe-password" :maxlength="maxlength" :disabled="disabled" :value="inputValue" @input="onInput" :placeholder="placeholder" :name="name">
    <input v-if="type === 'nickname'" type="nickname" :maxlength="maxlength" :disabled="disabled" :value="inputValue" @input="onInput" :placeholder="placeholder" :name="name">
    <input v-if="type === 'text'" type="text" :disabled="disabled" :value="inputValue" @input="onInput" :placeholder="placeholder" :name="name">
  </view>
</template>

<script lang="ts" setup>

import {inject, ref, watchEffect} from "vue";

interface CuInputProps {
  required?: boolean
  title: string
  placeholder?: string
  name?: string
  type?: 'text' | 'number' | 'idcard' | 'digit' | 'safe-password' | 'nickname',
  disabled?: boolean
  maxlength?: number | string
}
const props = withDefaults(defineProps<CuInputProps>(), {
  required: false,
  disabled: false,
  type: 'text',
  maxlength: '50'
})
const emit = defineEmits(['update:modelValue']);

const fields = inject<any>('fields')
const validate = inject<any>('validate')

const inputValue = ref('')

function onInput(e: any){
  const value = e.detail.value
  if (props.name){
    fields[props.name] = value
  }
  emit('update:modelValue',value)
}

watchEffect(() => {
  if (props.name){
    inputValue.value = fields[props.name]
    if (props.required){
      validate[props.name] = inputValue.value && inputValue.value.length > 0
    }
  }
})


</script>

<style>

</style>
